/*******************************************************************************
*  file    : myproxymodel.cpp
*  created : 04.09.2013
*  author  : Slyshyk Oleksiy (alexSlyshyk@gmail.com)
*******************************************************************************/

#include "deviceproxymodel.hpp"
#include "devicemodel.hpp"
#include <QBrush>

DeviceProxyModel::DeviceProxyModel(QObject *parent) :
    QSortFilterProxyModel(parent),
    sorting_(Sortings::Sort_AZ)
{
}

void DeviceProxyModel::sortAZ()
{
    sorting_ = Sortings::Sort_AZ;
    this->sort(DM_NAME_IDX, Qt::AscendingOrder);
}

void DeviceProxyModel::sortSmsDate()
{
    sorting_ = Sortings::Sort_SMS_Date;
    this->sort(DM_MEMO_IDX, Qt::AscendingOrder);
}

void DeviceProxyModel::sortBat()
{
    sorting_ = Sortings::Sort_Bat;
    this->sort(DM_STATUS_IDX, Qt::AscendingOrder);
}

void DeviceProxyModel::sortColor()
{
    sorting_ = Sortings::Sort_Color;
    this->sort(DM_PHONE_NUMBER_IDX, Qt::AscendingOrder);
}

void DeviceProxyModel::sortBatChange()
{
    sorting_ = Sortings::Sort_Bat_Change;
    this->sort(DM_BAT_CHANGE_IDX,Qt::AscendingOrder);
}

bool DeviceProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const
{
    switch(sorting_)
        {
        case Sortings::Sort_AZ:
        case Sortings::Sort_Bat_Change:
            return (left.data().toString() < right.data().toString()) ;
        case Sortings::Sort_Bat:
            {
                QStringList lft = left.data(DM_LAST_INFO_ROLE).toString().split(";");
                QStringList rgt = right.data(DM_LAST_INFO_ROLE).toString().split(";");
                auto get_bat = [](const QStringList& lst)->int
                    {
                        int bat = 0;
                        for(const QString& line : lst)
                            {
                                if(line.contains("BAT"))
                                    bat = line.split(":")[1].remove("%").toInt();
                            }
                        return bat;
                    };
                return ( get_bat(lft) > get_bat(rgt) );
            }
        case Sortings::Sort_Color:
            {
                QColor left_color,right_color;
                left_color  = left .data(Qt::BackgroundRole).value<QBrush>().color();
                right_color = right.data(Qt::BackgroundRole).value<QBrush>().color();
                return left_color.name() < right_color.name() ;
            }
        case Sortings::Sort_SMS_Date:
            return left.data(DM_LAST_SMS_DATE).toString() > right.data(DM_LAST_SMS_DATE).toString();
            break;
        }
    return false;
}
